import api from '../api/index'
import store from './index'

export function updateUser ({commit}, data) {
  return commit('updateUser', data)
}

export function updateToken ({commit}, token) {
  return commit('updateToken', token)
}

export function getUser ({commit}) {
  if (store.state.user !== null) {
    return commit('updateUser', store.state.user)
  }
  return api.getUserInfo().then(function (data) {
    if (data.code === 0) {
      return commit('updateUser', data.data.user)
    }
  })
}

export function updateWs ({commit}, ws) {
  return commit('updateWs', ws)
}

export function getWs ({commit}) {
  if (store.state.ws !== null) {
    return commit('updateWs', store.state.ws)
  } else {
    var ws = null
    ws = new WebSocket(window.wsUrl)
    ws.onopen = function () {
      var msg = {
        'msg_id': 1,
        'msg_data': {
          'token': store.getters.token
        }
      }
      if (ws.readyState === ws.OPEN) {
        console.log('websocket: open')
        ws.send(JSON.stringify(msg))
      }
    }
    ws.onmessage = function (e) {
      var data = JSON.parse(e.data)
      commit('pushMsg', data)
    }
    ws.onerror = function (e) {
      console.log('websocket error: ', e)
    }
    ws.onclose = function () {
      console.log('websocket close')
    }
    return commit('updateWs', ws)
  }
}

export function pushMsg ({commit}, msg) {
  return commit('pushMsg', msg)
}
